import 'package:baby_health_tracker/service/onboarding_service.dart';
import 'package:flutter/material.dart';
import '../model/baby.dart';
import '../service/database_service.dart';
import '../widgets/edit_baby_dialog.dart';

class OnboardingScreen extends StatelessWidget {
  const OnboardingScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '你好！',
                style: Theme.of(context).textTheme.headlineLarge,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 32),
              Text(
                '欢迎使用宝宝健康追踪',
                style: Theme.of(context).textTheme.headlineMedium,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              Text(
                '让我们开始记录宝宝的健康成长吧！\n首先添加宝宝的基本信息。',
                style: Theme.of(context).textTheme.bodyLarge,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 32),
              ElevatedButton.icon(
                icon: const Icon(Icons.add),
                label: const Text('添加宝宝信息'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 32,
                    vertical: 16,
                  ),
                ),
                onPressed: () => _addFirstBaby(context),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _addFirstBaby(BuildContext context) async {
    final result = await showDialog<Baby>(
      context: context,
      barrierDismissible: false,
      builder: (context) => const EditBabyDialog(),
    );

    if (result != null) {
      try {
        final baby = result.copyWith(isDefault: true);
        await DatabaseService().addBaby(baby);
        final onboarding = await OnboardingService.getInstance();
        await onboarding.completeOnboarding();
        if (context.mounted) {
          Navigator.of(context).pushReplacementNamed('/home');
        }
      } catch (e) {
        debugPrint(e.toString());
        if (context.mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('添加宝宝信息失败，请重试')));
        }
      }
    }
  }
}
